<?php

namespace App\Http\Controllers\Admin\Happy;

use App\Enums\CriticalEnum;
use App\Enums\Happy;
use App\Jobs\QiPao\ExcelJob;
use App\Services\Tools\DateTime;
use Carbon\Carbon;
use App\Enums\LuckyTree;
use App\Response\Response;
use App\Exceptions\BasicException;
use Couchbase\BaseException;
use Illuminate\Support\Facades\DB;
use \App\Http\Controllers\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class HappyController extends BaseController
{
    public function __construct(Request $request)
    {
        $this->is_next = $request->input('is_next', 0);
        if (!in_array($this->is_next, [0, 1])) {
            throw new BasicException(0, '参数有误');
        }
        $this->type = $request->input('type', 0);
        $this->pot_name = '';
        $this->type = $request->input('type', Happy::POOL_TYPE_HUNDRED_NEXT);
        if (isset(Happy::POOL_TYPE_CONFIG_NEXT[$this->type])) {
            $this->pot_name = Happy::POOL_TYPE_CONFIG_NEXT[$this->type];
        }
    }

    /**
     * @api {get} happy 本期奖池
     * @apiDescription type:1,2,3,4,5分别对应本期奖池的1连奖池,10连奖池,100连奖池,新手奖池,独立奖池;11,12,13,14,15分别对应下期奖池的1连奖池,10连奖池,100连奖池,新手奖池,独立奖池;30特殊奖池
     * @apiVersion 0.1.0
     * @apiName 本期奖池
     * @apiGroup 幸运树
     * @apiParam {numeric} type   奖池类型,非必传
     * @apiParam {numeric} is_next   是否下期奖池1是0否,默认0,非必传
     * @apiSuccessExample 成功响应
     */
    public function index(Request $request)
    {
        $isOpen = 0;
        $category = $request->get('category', 1);

        $types = app('repo_happy')->getJackpotType($category, $isOpen);
        $firstType = app('repo_happy')->getFirstType($types, $this->type);
        if (!$firstType) {
            throw new BasicException(0, '类型不存在或者错误，请刷新后重试');
        }
        $type =  $firstType['id'];
        $list = app('repo_happy')->getJackpotList($type, $this->is_next);

        return Response::sendData([
            'left'  => app('repo_happy')->getJackpotCount($type, $this->is_next),
            'total' => app('repo_happy')->getJackpotTotal($type, $this->is_next),
            'top' => $types,
            'type'  => $firstType['id'],
            'is_open' => $firstType['is_open'],
            'name'  => $firstType['name'],
            'list'  => $list,
        ]);
    }

    /**
     * @api {post} happy 添加修改本期奖池礼物
     * @apiVersion 0.1.0
     * @apiName 添加修改本期奖池礼物
     * @apiGroup 幸运树
     * @apiParam {numeric} type   奖池类型,非必传
     * @apiParam {numeric} is_next   是否下期奖池1是0否,默认0,非必传
     * @apiParam {numeric} id   如果传了id则为更新,否则添加,非必传
     * @apiParam {numeric} number   库存,必传
     * @apiParam {numeric} gift_id   礼物id,必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function update(Request $request)
    {
        if (!$this->type) {
            throw new BasicException(0, '奖池类型不能为空');
        }
        $data = $request->only(['gift_id', 'number']);
        $id = intval($request->input('id', 0));
        if (!isset($data['gift_id']) || $data['gift_id'] <= 0) {
            throw new BasicException(0, '请选择礼物');
        }
        if (!isset($data['number']) || $data['number'] < 0) {
            throw new BasicException(0, '数量不能小于0');
        }
        $correction_number = $request->get('correction_number', false);
        if ($correction_number === false) {
            $data['correction_number'] = $correction_number;
        }
        $model = $this->is_next ? 'model_happy_gift_next_pool' : 'model_happy_gift_pool';
        $data['updated_at'] = Carbon::now();
        if ($id > 0) {
            app($model)->where('id', $id)->update($data);
        } else {
            $exists = app($model)->where('type', $this->type)->where('gift_id', $data['gift_id'])->first();
            if ($exists) {
                throw new BasicException(0, '礼物已存在，请勿重复添加');
            }
            $data['type'] = $this->type;
            $data['created_at'] = Carbon::now();
            app($model)->insert($data);
        }

        return Response::sendData('success');
    }

    /**
     * @api {post} happy/all 一键修改本期奖池礼物
     * @apiVersion 0.1.0
     * @apiName 一键修改本期奖池礼物
     * @apiGroup 幸运树
     * @apiParam {numeric} type   奖池类型,非必传 1,2,3,4,5分别对应本期奖池的1连奖池,10连奖池,100连奖池,新手奖池,独立奖池;11,12,13,14,15分别对应下期奖池的1连奖池,10连奖池,100连奖池,新手奖池,独立奖池;30特殊奖池
     * @apiParam {numeric} is_next   是否下期奖池1是0否,默认0,非必传
     * @apiParam {numeric} gift_detail   礼物数据json  [{"gift_id":377,"gift_name":"拐杖糖","number":2301,"ratio":0}]
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function editAll(Request $request)
    {
        $v = app('validator')->make($request->all(),
            [
                'gift_detail' => 'required|string',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        if (!$this->type) {
            throw new BasicException(0, '奖池类型不能为空');
        }
        $data = $request->only(['gift_detail']);
        $giftDetailStr = $data['gift_detail'];
        $giftDetailList = json_decode($giftDetailStr, 1);
        $model = $this->is_next ? 'model_happy_gift_next_pool' : 'model_happy_gift_pool';
        foreach ($giftDetailList as $key => $value) {
            if (!isset($value['gift_id']) || $value['gift_id'] <= 0) {
                throw new BasicException(0, '请选择礼物');
            }
            if ($value['number'] < 0) {
                throw new BasicException(0, '数量不能小于0');
            }
            $whereArr = [];
            $whereArr[] = ["gift_id", "=", $value['gift_id']];
            $whereArr[] = ["type", "=", $this->type];
            app($model)->where($whereArr)->update(['number' => $value['number'], 'updated_at' => Carbon::now()]);
        }

        return Response::sendData('success');
    }

    /**
     * @api {delete} happy 删除本期奖池礼物
     * @apiVersion 0.1.0
     * @apiName 删除本期奖池礼物
     * @apiGroup 幸运树
     * @apiParam {numeric} id   主键id,必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function delete(Request $request)
    {
        $id = $request->input('id', 0);
        $model = $this->is_next ? 'model_happy_gift_next_pool' : 'model_happy_gift_pool';
        $detail = app($model)->where('id', $id)->first();
        if (!$detail) {
            throw new BasicException(0, '数据有误');
        }
        app($model)->where('id', $id)->delete();

        return Response::sendData('success');
    }

    /**
     * @api {get} happy/record 中奖纪录
     * @apiVersion 0.1.0
     * @apiName 中奖纪录
     * @apiGroup 幸运树
     * @apiParam {numeric} page   page,非必传
     * @apiParam {numeric} perPage   perPage,非必传
     * @apiParam {string} datemin   开始时间如2021-03-11,非必传
     * @apiParam {string} datemax   结束时间如2021-03-12,非必传
     * @apiParam {number} gift_id   礼物id,非必传
     * @apiParam {string} keyword   用户编号或昵称,非必传
     * @apiParam {int} is_flutter 是否飘屏记录，1：是，0：否，-1（默认）：全部
     * @apiSuccessExample 成功响应
     */
    public function record(Request $request)
    {
        $list = app('repo_happy')->getRecord($request);

        //        return Response::sendList($list);
        return Response::sendData($list);
    }

    /**
     * @api {post} happy/replace 替换奖池
     * @apiVersion 0.1.0
     * @apiName 替换奖池
     * @apiGroup 幸运树
     * @apiParam {numeric} type   奖池类型,必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function replace()
    {
        if (!$this->type) {
            throw new BasicException(0, '奖池类型不能为空');
        }

        app('repo_happy')->replaceJackpot($this->type);

        return Response::sendData(1);
    }

    /**
     * @api {post} happy/type/open 替换奖池
     * @apiVersion 0.1.0
     * @apiName 替换奖池
     * @apiGroup 幸运树
     * @apiParam {numeric} type   奖池类型,必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function typeOpen(Request $request)
    {
        $id = $request->input('id');
        $openType = $request->input('open_type');

        if (!in_array($openType, [0, 1])) {
            throw new BasicException(0, '开关参数有误');
        }

        app('repo_happy')->typeOpen($id, $openType);

        return Response::sendData(1);
    }

    /**
     * @api {get} happy/type/list 奖池类型列表
     * @apiVersion 0.1.0
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function typeList(Request $request)
    {
        $category = $request->input('category', 1);
        if (!in_array($category, [1, 2])) {
            throw new BasicException(0, '请选择奖池类型');
        }

        $list = app('repo_happy')->getJackpotType($category, 0);

        return Response::sendData($list);
    }

    /**
     * @api {post} happy/type/add 添加奖池类型
     * @apiVersion 0.1.0
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function typeAdd(Request $request)
    {
        $v = app('validator')->make($request->all(),
            [
                'name' => 'required|string',
                'remark' => 'required|string',
                'sort' => 'required|numeric',
                'category' => 'required|numeric|in:2',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $data = $request->only(['name', 'remark', 'sort', 'category']);
        $poolType = app('repo_happy')->getLastType();
        $data['id'] = ($poolType['id'] ?? 100) + 1;
        $res = app('repo_happy')->addType($data);
        if (!isset($res['id'])) {
            return Response::sendData(false);
        }
        return Response::sendData(true);
    }

    /**
     * @api {post} happy/type/add 添加奖池类型
     * @apiVersion 0.1.0
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function typeEdit(Request $request)
    {
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required|numeric',
                'name' => 'required|string',
                'remark' => 'required|string',
                'sort' => 'required|numeric',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $data = $request->only(['name', 'remark', 'sort']);
        $id = $request->get('id');
        if (!$id) {
            throw new BasicException(10001, '请选择要编辑的奖池类型');
        }
        $res = app('repo_happy')->editType($id, $data);
        if (!$res) {
            return Response::sendData(false);
        }
        return Response::sendData(true);
    }


    /**
     * @api {post} happy/type/add 添加奖池类型
     * @apiVersion 0.1.0
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function typeDestory(Request $request)
    {
        $id = $request->get('id');
        if (!$id) {
            throw new BasicException(10001, '请选择要删除的奖池类型');
        }
        if ($id == 100) {
            throw new BasicException(10001, '此奖池无法删除');
        }
        $res = app('repo_happy')->delType($id);
        if (!$res) {
            return Response::sendData(false);
        }
        return Response::sendData(true);
    }

    /**
     * @api {get} happy/supply 补池
     * @apiVersion 0.1.0
     * @apiName 补池列表
     * @apiSuccessExample 成功响应
     */
    public function supply()
    {
        $type = Happy::POOL_TYPE_SUPPLY_NEXT;
        if ($this->type != $type) {
            throw new BasicException(0, '非法访问');
        }
        $data = app('repo_happy')->getJackpotList($type, $this->is_next);
        // 查询中奖礼物数
        $giftIds = $data->pluck('gift_id');
        if (!empty($giftIds)) {
            $result = DB::table('ln_happy_game_log')
                ->whereIn('gift_id', $giftIds)
                ->where('type', $type)
                ->selectRaw('sum(number) as count,gift_id')
                ->groupBy('gift_id')
                ->get()->toArray();
            $map = array_column($result, 'count', 'gift_id');
            foreach ($data as &$value) {
                $value->count = $map[$value->gift_id] ?? 0;
            }
        }

        $ratioConfig = app('repo_happy')->getRatioConfig();

        return Response::sendData([
            'left'  => app('repo_happy')->getJackpotCount($type, $this->is_next),
            'total' => app('repo_happy')->getJackpotTotal($type, $this->is_next),
            'type'  => (int) $type,
            'name'  => '补池列表',
            'ratio' => $ratioConfig,
            'list'  => $data,
        ]);
    }

    /**
     * @api {post} happy/supply/ratio 更新产出比
     * @apiVersion 0.1.0
     * @apiName 更新产出比
     * @apiGroup 幸运树
     * @apiParam {numeric} min_ratio   库存产出投入比最低下限,必传
     * @apiParam {numeric} max_ratio   库存产出投入比最大上限,必传
     * @apiParam {numeric} min_self_ratio   个人产出投入比最低下限,必传
     * @apiParam {numeric} max_self_ratio   个人产出投入比最大上限,必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function updateSupplyRatio(Request $request)
    {
        $key = 'happy:ratio_config';
        $minRatio = $request->input('min_ratio');
        $maxRatio = $request->input('max_ratio');
        $minSelfRatio = $request->input('min_self_ratio');
        $maxSelfRatio = $request->input('max_self_ratio');
        if ($minRatio <= 0 || $maxRatio <= 0 || $minSelfRatio <= 0 || $maxSelfRatio <= 0) {
            throw new BasicException(0, '概率配置不能小于等于0');
        }
        $redis = app('redis');
        $ratioConfig = [
            'min_ratio'      => $minRatio,
            'max_ratio'      => $maxRatio,
            'min_self_ratio' => $minSelfRatio,
            'max_self_ratio' => $maxSelfRatio,
        ];
        $redis->set($key, json_encode($ratioConfig));
        return Response::sendData(1);
    }

    /**
     * @api {post} happy/ratio 更新产出比
     * @apiVersion 0.1.0
     * @apiName 更新产出比
     * @apiGroup 幸运树
     * @apiParam {numeric} user_incoin   库存产出投入比最低下限,必传
     * @apiParam {numeric} user_outcoin   库存产出投入比最大上限,必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function updateRatio(Request $request)
    {
        $key = 'happy:supply_ratio_config';
        $userIncoin = $request->input('user_incoin');
        $userOutcoin = $request->input('user_outcoin');
        if ($userIncoin <= 0 || $userOutcoin <= 0) {
            throw new BasicException(0, '投入及产出配置不能小于等于0');
        }
        $redis = app('redis');
        $userRatioConfig = [
            'user_incoin'  => $userIncoin,
            'user_outcoin' => $userOutcoin,
        ];
        $redis->set($key, json_encode($userRatioConfig));

        return Response::sendData(1);
    }

    /**
     * @api {get} happy/user/ratio 用户产出比列表
     * @apiVersion 0.1.0
     * @apiName 用户产出比列表
     * @apiGroup 幸运树
     * @apiParam {number} user_code 用户编号,非必传
     * @apiParam {number} nickname 用户昵称
     * @apiParam {number} mobile 用户编号,非必传
     * @apiParam {number} type 用户编号,非必传 与output配合使用 实际产出比 筛选 1:>output  2:<output 3：=output
     * @apiParam {number} output 用户编号,非必传
     * @apiParam {number} output_order 1根据id排序 2根据实际投入产出比 升序 3根据实际投入产出比 降序
     * @apiParam {string} last_lottery_time_start 最后抽奖时间开始
     * @apiParam {string} last_lottery_time_end 最后抽奖时间结束
     * @apiParam {number} perPage 页码 ，非必传 默认20
     * @apiParam {number} page 用户编号,非必传
     * @apiSuccessExample 成功响应
     */
    public function userRatio(Request $request)
    {
        $keyword = $request->input('user_code');
        $nickname = $request->input('nickname', null);
        $mobile = $request->input('mobile', null);
        $output = $request->input('output', null);
        $type = $request->input('type', null);             //>= or <=
        $ordertype = $request->input('output_order', 1);   //>= or <=
        $lastLotteryTimeStart = $request->input('last_lottery_time_start', '');
        $lastLotteryTimeEnd = $request->input('last_lottery_time_end', '');
        $page = $request->input('page', 20);               //>= or <=
        $perPage = $request->input('perPage', 20);
        $data = $request->only(['user_code', 'nickname', 'mobile', 'output', 'type', 'output_order', 'perPage']);
        $va = app('validator')->make($data, [
            'perPage'      => 'integer|min:1',
            'page'         => 'integer|min:1',
            'user_code'    => 'integer|min:1',
            'mobile'       => 'string|max:11',
            'output_order' => 'in:1,2,3',//根据id排序 2根据实际投入产出比 升序 3根据实际投入产出比 降序
            'output'       => 'numeric|min:0',
            'type'         => 'integer|in:1,2,3',//1:> 2:< 3:=

        ]);
        if ($va->fails()) {
            throw  new BasicException(10001, $va->errors()->first());
        }

        $where = [
            ['base.id', '>', 0],
        ];
        if ($keyword) {
            $where[] = ['ud.user_code', '=', $keyword];
        }
        if ($nickname) {
            $where[] = ['ud.nickname', 'like', '%' . $nickname . "%"];
        }
        if ($mobile) {
            $where[] = ['u.mobile', '=', $mobile];
        }


        if ($type && $type == 1 && $output) {
            $where[] = [DB::raw("ROUND(base.outcoin_total/base.incoin_total,2)"), '>', intval($output)];
        }
        if ($type && $type == 2 && $output) {
            $where[] = [DB::raw("ROUND(base.outcoin_total/base.incoin_total,2)"), '<', $output];
        }
        if ($type && $type == 3 && $output) {
            $where[] = [DB::raw("ROUND(base.outcoin_total/base.incoin_total,2)"), '=', $output];
        }
        if ($lastLotteryTimeStart) {
            $where[] = ['base.updated_at', '>=', $lastLotteryTimeStart];
        }
        if ($lastLotteryTimeEnd) {
            $where[] = ['base.updated_at', '<=', $lastLotteryTimeEnd];
        }

        $order = [];
        if ($ordertype == 1) {
            $order['field'] = 'base.id';
            $order['way'] = 'desc';
        } elseif ($ordertype == 2) {
            $order['field'] = 'current_ratio_real';
            $order['way'] = 'asc';
        } else {
            $order['field'] = 'current_ratio_real';
            $order['way'] = 'desc';
        }

        $field = [
            DB::raw('ROUND(base.outcoin_total/base.incoin_total,2) as current_ratio_real'),
            'base.id',
            'u.mobile',
            'base.incoin_total',
            'base.outcoin_total',
            'ud.nickname',
            'ud.head_picture',
            'ud.user_code',
        ];

        $list = DB::table('ln_happy_user_record as base')
            ->leftJoin('ln_user_data as ud', 'base.user_id', '=', 'ud.user_id')
            ->leftJoin('ln_user as u', 'base.user_id', '=', 'u.user_id')
            ->select($field)
            ->where($where)
            ->orderBy($order['field'], $order['way'])
            ->paginate($perPage);

        $userRatioConfigKey = 'happy:user_ratio_config';
        $redis = app('redis');
        $userRatioConfig = $redis->get($userRatioConfigKey);

        if (empty($userRatioConfig)) {
            $userRatioConfig = [
                'user_incoin'  => 20000,
                'user_outcoin' => 20000,
            ];
            $redis->set($userRatioConfigKey, json_encode($userRatioConfig));
        } else {
            $userRatioConfig = json_decode($userRatioConfig, true);
        }

        $list->getCollection()->transform(function ($value) use ($userRatioConfig) {
            if ($value->incoin_total > 2 * $userRatioConfig['user_incoin'] && $value->outcoin_total > 2 * $userRatioConfig['user_outcoin']) {//用户投入产出都在计划的两倍以上
                $timesIncoin = ceil($value->incoin_total / $userRatioConfig['user_incoin']);                                                 //用户实际投入/计划投入 倍率
                $timesOutcoin = ceil($value->outcoin_total / $userRatioConfig['user_outcoin']);
                $times = min($timesIncoin, $timesOutcoin);
                $value->current_incoin_total = $value->incoin_total - ($times - 2) * $userRatioConfig['user_incoin'];
                $value->current_outcoin_total = $value->outcoin_total - ($times - 2) * $userRatioConfig['user_outcoin'];
                $value->current_ratio = round($value->current_outcoin_total / $value->current_incoin_total, 2);
            } else {
                $value->current_incoin_total = $value->incoin_total;
                $value->current_outcoin_total = $value->outcoin_total;
                $value->current_ratio = $value->current_incoin_total == 0 ? 0 : round($value->current_outcoin_total / $value->current_incoin_total, 2);
            }

            return $value;
        });

        return Response::sendList($list, [], $userRatioConfig);
    }

    /**
     * @api {post} happy/user/ratio 用户投入产出比配置修改
     * @apiVersion 0.1.0
     * @apiName 用户投入产出比配置修改
     * @apiGroup 幸运树
     * @apiParam {numeric} user_incoin   用户理论投入,必传
     * @apiParam {numeric} user_outcoin   用户理论产出,必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": "success"
     * }
     */
    public function updateUserRatio(Request $request)
    {
        $key = 'happy:user_ratio_config';
        $userIncoin = $request->input('user_incoin');
        $userOutcoin = $request->input('user_outcoin');
        if ($userIncoin <= 0 || $userOutcoin <= 0) {
            throw new BasicException(0, '投入及产出配置不能小于等于0');
        }
        $redis = app('redis');
        $userRatioConfig = [
            'user_incoin'  => $userIncoin,
            'user_outcoin' => $userOutcoin,
        ];
        $redis->set($key, json_encode($userRatioConfig));

        return Response::sendData(1);
    }

    /**
     * @api {get} happy/independent 节奏用户列表
     * @apiVersion 0.1.0
     * @apiName 独立奖池
     * @apiGroup 幸运树
     * @apiSuccessExample 成功响应
     */
    public function independent(Request $request)
    {
        $perPage = $request->input('perPage', 20);
        $page = $request->input('page', 1);
        $list = app('model_happy_special_user')
            ->select([
                'incoin_total',
                'outcoin_total',
                'add_time',
                'status',
                'id',
                'user_id',
                'expired_time',
            ])
            ->with([
                'user_data:user_id,nickname,user_code,head_picture',
                'types',
                'types.type',
            ])
            ->when($request->get('user_code', false),function ($query, $value) {
                $query->where('a.user_code', $value);
            })
            ->paginate($perPage);

        foreach ($list as $k => $v) {
            $v['nickname'] = $v['user_data']['nickname'] ?? '';
            $v['user_code'] = $v['user_data']['user_code'] ?? '';
            $v['head_picture'] = $v['user_data']['head_picture'] ?? '';
            unset($v['user_data']);
            $v['type'] = collect(collect($v['types'])->pluck('type'))->pluck(['name'])->implode('、');
            $v['type_id'] = collect($v['types'])->pluck('type_id');
            $v['is_current'] = in_array(1, collect($v['types'])->pluck('is_current')->toArray()) ? 1 : 0;
            unset($v['types']);
            $v['expired_time'] = date('Y-m-d H:i:s', $v['expired_time']);
            $v['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
        }

        return Response::sendList($list);
    }

    /**
     * @api {post} happy/independent 添加节奏奖池
     */
    public function updateIndependent(Request $request)
    {
        $data = $request->only(['user_code', 'expired_time', 'types']);
        if (!isset($data['user_code']) || !$data['user_code']) {
            throw new BasicException(0, '请输入用户id');
        }
        if (!isset($data['expired_time']) || !$data['expired_time']) {
            throw new BasicException(0, '请输入过期时间');
        }
        if (!isset($data['types']) || !$data['types']) {
            throw new BasicException(0, '请选择绑定奖池');
        }
        $user = app('model_user_data')->where('user_code', $data['user_code'])->first();
        if (!$user) {
            throw new BasicException(0, '用户不存在');
        }
        $typeArr = explode(',', trim($data['types'], ','));
        foreach ($typeArr as $k => $v) {
            $poolType = app('model_happy_pools_type')->where('category', 2)->where('id', $v)->first();
            if (!$poolType) {
                throw new BasicException(0, '绑定奖池错误，请刷新以后重试');
            }
        }

        DB::beginTransaction();
        try {
            DB::table('ln_happy_special_user')->where('user_id', $user->user_id)->delete();
            DB::table('ln_happy_special_user_pools')->where('user_id', $user->user_id)->delete();
            DB::table('ln_happy_special_user')->insert([
                'user_id'       => $user->user_id,
                'nickname'      => $user->nickname,
                'user_code'     => $data['user_code'],
                'add_time'      => Carbon::now()->timestamp,
                'expired_time'  => Carbon::parse($data['expired_time'])->timestamp,
                'status'        => 1,
                'created_at'    => Carbon::now()->timestamp,
                'updated_at'    => Carbon::now()->timestamp,
            ]);
            $insertData = [];
            foreach ($typeArr as $k => $v) {
                $insertData[] = [
                    'user_id' => $user->user_id,
                    'type_id' => $v,
                    'created_at'    => Carbon::now(),
                    'updated_at'    => Carbon::now(),
                ];
            }
            DB::table('ln_happy_special_user_pools')->insert($insertData);

        } catch (\Exception $e) {
            DB::rollBack();
            $message = $e->getMessage();
            Log::error("添加节奏奖池失败,error:".$message);
            throw new BasicException(0, $message);
        }
        DB::commit();

        return Response::sendData(1);
    }

    /**
     * @api {delete} happy/independent 删除节奏用户
     */
    public function deleteIndependent(Request $request)
    {
        $id = $request->input('id');
        if (!$id) {
            throw new BasicException(10001);
        }
        $detail = DB::table('ln_happy_special_user')->where('id', $id)->first();
        if (!$detail) {
            throw new BasicException(10008);
        }

        DB::beginTransaction();
        try {
            DB::table('ln_happy_special_user_pools')->where('user_id', $detail->user_id)->delete();
            DB::table('ln_happy_special_user')->where('id', $id)->delete();
        } catch (\Exception $e) {
            DB::rollBack();
            $message = $e->getMessage();
            Log::error("删除节奏奖池失败,error:".$message);
            throw new BasicException(0, $message);
        }
        DB::commit();
        return Response::sendData(1);
    }

    /**
     * @api {get} happy/user/independent 节奏用户本期奖池
     */
    public function userIndependent(Request $request)
    {
        $data = $request->only(['user_code']);
        if (!isset($data['user_code']) || !$data['user_code']) {
            throw new BasicException(0, '请输入用户id');
        }
        $user = app('model_user_data')->where('user_code', $data['user_code'])->first();
        if (!$user) {
            throw new BasicException(0, '用户不存在');
        }
        $userPool = DB::table('ln_happy_special_user_pools')->where('user_id', $user->user_id)->where('is_current', 1)->first();
        if (!$userPool) {
            return Response::sendData([]);
        }
        $firstType = app('model_happy_pools_type')->where('id', $userPool->type_id)->first();
        if (!$firstType) {
            throw new BasicException(0, '奖池不存在，请检查是否已删除此用户奖池');
        }
        $list = app('repo_happy')->getJackpotList($userPool->type_id, false);
        return Response::sendData([
            'type'  => $firstType->id,
            'is_open' => $firstType->is_open,
            'name'  => $firstType->name,
            'nickname'  => $user->nickname,
            'list'  => $list,
        ]);
    }

    /**
     * @Desc:统计数据-总数据
     * @return string
     */
    public function allData()
    {
        $data = app('repo_happy')->allData();

        return Response::sendData($data);
    }

    /**
     * @Desc:盈利/亏损用户列表
     * @param  Request  $request
     * @return string
     * @throws BasicException
     */
    public function usersList(Request $request)
    {
        //数据过滤
        $v = app('validator')->make($request->all(), [
            'page_size' => 'filled|numeric',
            'page' => 'filled|numeric',
            'user_code' => 'filled|string',
            'type' => 'required|in:1,2'
        ]);

        if ($v->fails()) {
            throw new BasicException(10010, getValidateMessage($v->messages()));
        }
        $params = $request->input();
        $params['user_code'] = $params['user_code'] ?? -1;
        $params['page'] = $params['page'] ?? 1;
        $params['page_size'] = $params['page_size'] ?? 10;
        $params['start_time'] = $params['start_time'] ?? '';
        $params['end_time'] = $params['end_time'] ?? '';
        $params['time_type'] = $params['time_type'] ?? 0;
        if ($params['time_type'] == 1){     //今日
            $dateRange = [date('Y-m-d'), date('Y-m-d')];
            $params['start_time'] = $dateRange[0];
            $params['end_time'] = $dateRange[1];
        } elseif ($params['time_type'] == 2){   //本周
            $dateRange = DateTime::getWeekDateRange();
            $params['start_time'] = $dateRange[0];
            $params['end_time'] = $dateRange[1];
        } elseif ($params['time_type'] == 3){       //本月
            $dateRange = DateTime::getMonthDateRange();
            $params['start_time'] = $dateRange[0];
            $params['end_time'] = $dateRange[1];
        }
        if (strtotime($params['end_time']) - strtotime($params['start_time']) > 180 * 86400) {
            throw new BasicException(0, '日期范围不能超过180天');
        }
        if (!empty($params['start_time'])){
            $params['start_time'] = $params['start_time'].' 00:00:00';
        }

        if (!empty($params['end_time'])){
            $params['end_time'] = $params['end_time'].' 23:59:59';
        }

        $profitData = app('repo_happy')->userList($params);

        return Response::sendData($profitData);
    }


    /**
     * @Desc:列表导出
     * @param  Request  $request
     * @return string
     * @throws BasicException
     */
    public function export(Request $request)
    {
        //数据过滤
        $v = app('validator')->make($request->all(), [
            'page_size' => 'nullable|numeric',
            'page' => 'nullable|numeric',
            'user_code' => 'nullable|string',
            'type' => 'required|in:1,2',
        ]);

        if ($v->fails()) {
            throw new BasicException(10010, getValidateMessage($v->messages()));
        }
        $params = $request->all();
        $params['time_type'] = $params['time_type'] ?? 0;
        if ($params['time_type'] == 1){     //今日
            $dateRange = [date('Y-m-d'), date('Y-m-d')];
            $params['start_time'] = $dateRange[0];
            $params['end_time'] = $dateRange[1];
        } elseif ($params['time_type'] == 2){   //本周
            $dateRange = DateTime::getWeekDateRange();
            $params['start_time'] = $dateRange[0];
            $params['end_time'] = $dateRange[1];
        } elseif ($params['time_type'] == 3){       //本月
            $dateRange = DateTime::getMonthDateRange();
            $params['start_time'] = $dateRange[0];
            $params['end_time'] = $dateRange[1];
        }
        if (strtotime($params['end_time']) - strtotime($params['start_time']) > 180 * 86400) {
            throw new BasicException(0, '日期范围不能超过180天');
        }
        if (!empty($params['start_time'])){
            $params['start_time'] = $params['start_time'].' 00:00:00';
        }

        if (!empty($params['end_time'])){
            $params['end_time'] = $params['end_time'].' 23:59:59';
        }
        $type = $params['type'];
        if ($type == 1){
            /*奖池数据统计-盈利用户列表*/
            $data = [
                'admin_id'     => $request->admin_id ?? '',
                'data_no'      => 36,//ExportEnum::NO
                'condition'    => json_encode($params) ?? '',
                'status'       => 0,//正在导出
                'title'        => '欢乐大作战奖池数据统计-盈利用户列表 异步导出',//正在导出
                'download_url' => '',
            ];
            $exportLogId = app('model_admin_export_log')->insertGetId($data);
            $excel = new ExcelJob($exportLogId, $request->admin_id, 38, $params);
            // 标记导出程序开始运行
            dispatch($excel)->onQueue(env('RABBITMQ_QUEUE_EXCEL'));                    //推送到指定队列
        } else {
            /*奖池数据统计-亏损用户列表*/
            $data = [
                'admin_id'     => $request->admin_id ?? '',
                'data_no'      => 37,//ExportEnum::NO
                'condition'    => json_encode($params) ?? '',
                'status'       => 0,//正在导出
                'title'        => '欢乐大作战奖池数据统计-亏损用户列表 异步导出',//正在导出
                'download_url' => '',
            ];
            $exportLogId = app('model_admin_export_log')->insertGetId($data);
            $excel = new ExcelJob($exportLogId, $request->admin_id, 39, $params);
            // 标记导出程序开始运行
            dispatch($excel)->onQueue(env('RABBITMQ_QUEUE_EXCEL'));                    //推送到指定队列
        }

        return Response::sendData(true);
    }

}
